<template>
  <div class="access-control-info bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">门禁/卡口信息</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <!-- <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label for="parkCode" class="block text-sm font-medium">园区编号：</label>
          <input type="text" id="parkCode" v-model="search.parkCode" placeholder="请输入"
            class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
        </div>
        <div>
          <label for="equipName" class="block text-sm font-medium">设备名称：</label>
          <input type="text" id="equipName" v-model="search.equipName" placeholder="请输入"
            class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
        </div>
        <div>
          <label for="equipType" class="block text-sm font-medium">设备类型：</label>
          <select id="equipType" v-model="search.equipType"
            class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
            <option value="">全部</option>
            <option value="1">门禁</option>
            <option value="2">人员闸机</option>
            <option value="3">车辆卡口</option>
            <option value="4">车辆抓拍道闸</option>
          </select>
        </div>
        <div class="flex justify-end mt-4 space-x-2">
          <button @click="searchEquipment" class="btn btn-primary">查询</button>
          <button @click="resetSearch" class="btn btn-secondary">重置</button>
        </div>
      </div> -->
      <query-form :model="search" :formItems="formItems" @search="searchEquipment" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <!-- <button @click="openAddDialog" class="btn btn-primary">新增</button>
      <button @click="deleteSelected" class="btn btn-destructive">删除</button>
      <button @click="importData" class="btn btn-secondary">导入</button>
      <button @click="exportData" class="btn btn-secondary">导出</button> -->
      <el-button class="btn" type="primary" @click="openAddDialog" style="width: 75px; height: 30px;">新增</el-button>
      <el-button class="btn" @click="deleteSelected" style="width: 75px; height: 30px;">删除</el-button>
      <!-- <el-button @click="importData" style="width: 75px; height: 30px;">导入</el-button> -->
      <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground shadow-md rounded my-6">
      <!-- <table class="min-w-full table-auto">
        <thead>
          <tr class="bg-muted text-muted-foreground text-sm leading-normal">
            <th class="py-3 px-6 text-left">
              <input type="checkbox" :checked="selectAll" @change="toggleSelectAll">
            </th>
            <th class="py-3 px-6 text-left">园区编号</th>
            <th class="py-3 px-6 text-left">设备名称</th>
            <th class="py-3 px-6 text-left">设备类型</th>
            <th class="py-3 px-6 text-left">经度</th>
            <th class="py-3 px-6 text-left">纬度</th>
            <th class="py-3 px-6 text-left">操作</th>
          </tr>
        </thead>
        <tbody class="text-sm">
          <tr v-for="item in displayedEquipmentData" :key="item.ID" class="border-b border-border hover:bg-muted/50">
            <td class="py-3 px-6 text-left">
              <input type="checkbox" :checked="selectedIds.includes(item.ID)" @change="toggleItemSelection(item)">
            </td>
            <td class="py-3 px-6 text-left">{{ item.PARK_CODE }}</td>
            <td class="py-3 px-6 text-left">{{ item.EQUIP_NAME }}</td>
            <td class="py-3 px-6 text-left">{{ getEquipTypeText(item.EQUIP_TYPE) }}</td>
            <td class="py-3 px-6 text-left">{{ item.LONGITUDE }}</td>
            <td class="py-3 px-6 text-left">{{ item.LATITUDE }}</td>
            <td class="py-3 px-6 text-left">
              <button @click="viewDetails(item)" class="text-blue-600 hover:text-blue-900 mr-2">查看</button>
              <button @click="loadRecordForUpdate(item)" class="text-green-600 hover:text-green-900 mr-2">编辑</button>
              <button @click="confirmDelete(item.ID)" class="text-red-600 hover:text-red-900">删除</button>
            </td>
          </tr>
        </tbody>
      </table> -->
      <el-table v-loading="loading" :data="displayedEquipmentData" style="width: 100%"
        @selection-change="handleSelectionChange" ref="table" align="center" class="data-table"
        :header-cell-style="headerCellStyle">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="编号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ startIndex + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="PARK_CODE" label="园区编号" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EQUIP_NAME" label="设备名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EQUIP_TYPE" label="设备类型" header-align="center" align="center">
          <template #default="scope">
            {{ getEquipTypeText(scope.row.EQUIP_TYPE) }}
          </template>
        </el-table-column>
        <el-table-column prop="LONGITUDE" label="经度" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LATITUDE" label="纬度" header-align="center" align="center"></el-table-column>
      </el-table>
    </div>


    <!-- Pagination -->
    <!-- <div
      class="flex items-center justify-between px-4 py-3 bg-card text-card-foreground border-t border-border sm:px-6">
      <div class="flex items-center">
        <span class="mr-2">每页显示</span>
        <select v-model="pageSize" @change="changePageSize"
          class="rounded border-input bg-background text-foreground shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
          <option :value="10">10</option>
          <option :value="20">20</option>
          <option :value="50">50</option>
        </select>
        <span class="ml-2">条</span>
      </div>
      <div class="flex items-center">
        <button @click="prevPage" :disabled="currentPage === 1"
          class="px-3 py-1 rounded bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed mr-1">&lt;</button>
        <button v-for="page in displayedPages" :key="page" @click="goToPage(page)" :class="[
          'px-3 py-1 rounded mr-1',
          currentPage === page
            ? 'bg-primary text-primary-foreground cursor-default'
            : 'bg-secondary text-secondary-foreground hover:bg-secondary/80'
        ]" :disabled="currentPage === page">
          {{ page }}
        </button>
        <button @click="nextPage" :disabled="currentPage === totalPages"
          class="px-3 py-1 rounded bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed ml-1">&gt;</button>
        <span class="ml-2">跳至</span>
        <input v-model.number="jumpToPage" @keyup.enter="goToPage(jumpToPage)" type="number" min="1" :max="totalPages"
          class="w-16 rounded border-input bg-background text-foreground shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50 mx-2">
        <span>页</span>
      </div>
    </div> -->
    <div
      class="flex items-center justify-between px-4 py-3 bg-card text-card-foreground border-t border-border sm:px-6">
      <!-- <div>共检索到 {{ totalItems }} 条信息</div>
      <div class="flex space-x-2">
        <button v-for="page in totalPages" :key="page" @click="currentPage = page" :class="[
          'rounded border px-3 py-1',
          currentPage === page
            ? 'bg-primary text-primary-foreground'
            : 'bg-card text-card-foreground',
        ]">
          {{ page }}
        </button>
      </div> -->
      <div>
        <p class="text-sm text-muted-foreground">
          一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
          下一页
        </button>
      </div>
    </div>
    <!-- Add Equipment Dialog -->
    <!-- <Teleport to="body">
      <div v-if="isAddDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[500px]">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-bold">新增门禁/卡口信息</h3>
            <button @click="closeAddDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-4">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label for="newParkCode" class="block text-sm font-medium text-gray-700">园区编号：</label>
                <input type="text" id="newParkCode" v-model="newRecord.PARK_CODE" placeholder="请输入"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
              </div>
              <div>
                <label for="newEquipName" class="block text-sm font-medium text-gray-700">设备名</label>
                <input type="text" id="newEquipName" v-model="newRecord.EQUIP_NAME" placeholder="请输入"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
              </div>
              <div>
                <label for="newEquipType" class="block text-sm font-medium text-gray-700">设备类型：</label>
                <select id="newEquipType" v-model="newRecord.EQUIP_TYPE"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                  <option value="">请选择</option>
                  <option value="1">门禁</option>
                  <option value="2">人员闸机</option>
                  <option value="3">车辆卡口</option>
                  <option value="4">车辆抓拍道闸</option>
                </select>
              </div>
              <div>
                <label for="newLongitude" class="block text-sm font-medium text-gray-700">经度：</label>
                <input type="number" id="newLongitude" v-model="newRecord.LONGITUDE" step="0.000001" placeholder="请输入"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
              </div>
              <div>
                <label for="newLatitude" class="block text-sm font-medium text-gray-700">纬度：</label>
                <input type="number" id="newLatitude" v-model="newRecord.LATITUDE" step="0.000001" placeholder="请输入"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
              </div>
              <div>
                <label for="newCreateBy" class="block text-sm font-medium text-gray-700">创建人：</label>
                <input type="text" id="newCreateBy" v-model="newRecord.CREATE_BY" placeholder="请输入"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
              </div>
            </div>
          </div>

          <div class="flex justify-end space-x-2 mt-6">
            <button @click="closeAddDialog"
              class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-offset-2">
              取消
            </button>
            <button @click="addNewEquipment"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">
              确认
            </button>
          </div>
        </div>
      </div>
    </Teleport> -->
    <el-dialog class="dialog-from" v-model="isAddDialogOpen" :title="isDialogType == 'add' ? '门禁/卡口新增' : '门禁/卡口编辑'"
      width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="newRecord" label-width="auto" :rules="rules" ref="formRef">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="园区编号：" label-position="top" prop="PARK_CODE">
                  <el-input v-model="newRecord.PARK_CODE" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备名称：" label-position="top" prop="EQUIP_NAME">
                  <el-input v-model="newRecord.EQUIP_NAME" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备类型：" label-position="top" prop="EQUIP_TYPE">
                  <el-select v-model="newRecord.EQUIP_TYPE" placeholder="请选择" clearable>
                    <el-option label="门禁" value="1" />
                    <el-option label="人员闸机" value="2" />
                    <el-option label="车辆卡口" value="3" />
                    <el-option label="车辆抓拍道闸" value="4" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="经度：" label-position="top" prop="LONGITUDE">
                  <el-input type="number" v-model="newRecord.LONGITUDE" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="纬度：" label-position="top" prop="LATITUDE">
                  <el-input type="number" v-model="newRecord.LATITUDE" />
                </el-form-item>
              </el-col>
              <el-col :span="8"></el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <!-- <span>
        Notice: before dialog gets opened for the first time this node and the one
        bellow will not be rendered
      </span>
      <div>
        <strong>Extra content (Not rendered)</strong>
      </div> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addNewEquipment">确认</el-button>
          <el-button @click="isAddDialogOpen = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- View Details Dialog -->
    <Teleport to="body">
      <div v-if="isViewDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-96">
          <h3 class="text-lg font-bold mb-4">查看设备详情</h3>
          <div v-if="selectedItem">
            <p><strong>园区编号：</strong>{{ selectedItem.PARK_CODE }}</p>
            <p><strong>设备名称：</strong>{{ selectedItem.EQUIP_NAME }}</p>
            <p><strong>设备类型：</strong>{{ getEquipTypeText(selectedItem.EQUIP_TYPE) }}</p>
            <p><strong>经度：</strong>{{ selectedItem.LONGITUDE }}</p>
            <p><strong>纬度：</strong>{{ selectedItem.LATITUDE }}</p>
          </div>
          <div class="mt-4 flex justify-end">
            <button @click="closeViewDialog"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">关闭</button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- Edit Dialog -->
    <Teleport to="body">
      <div v-if="isEditDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[500px]">
          <h3 class="text-lg font-bold mb-4">编辑设备信息</h3>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label for="editParkCode" class="block text-sm font-medium text-gray-700">园区编号：</label>
              <input type="text" id="editParkCode" v-model="updateData.PARK_CODE"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="editEquipName" class="block text-sm font-medium text-gray-700">设备名称：</label>
              <input type="text" id="editEquipName" v-model="updateData.EQUIP_NAME"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="editEquipType" class="block text-sm font-medium text-gray-700">设备类型：</label>
              <select id="editEquipType" v-model="updateData.EQUIP_TYPE"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                <option value="1">门禁</option>
                <option value="2">人员闸机</option>
                <option value="3">车辆卡口</option>
                <option value="4">车辆抓拍道闸</option>
              </select>
            </div>
            <div>
              <label for="editLongitude" class="block text-sm font-medium text-gray-700">经度：</label>
              <input type="number" id="editLongitude" v-model="updateData.LONGITUDE" step="0.000001"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="editLatitude" class="block text-sm font-medium text-gray-700">纬度：</label>
              <input type="number" id="editLatitude" v-model="updateData.LATITUDE" step="0.000001"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
          </div>
          <div class="mt-4 flex justify-end space-x-2">
            <button @click="closeEditDialog"
              class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-offset-2">取消</button>
            <button @click="updateEquipment"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">确认</button>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()

const apiBaseUrl = ref(proxy.$currentUrl + '/api/equipment')

// 搜索相关
const search = ref({
  PARK_CODE: '',
  EQUIP_NAME: '',
  EQUIP_TYPE: ''
})

// 数据相关
const equipmentData = ref([])
const selectAll = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const jumpToPage = ref(1)

// 对话框状态
const isAddDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const isEditDialogOpen = ref(false)

// 新记录和更新记录
const newRecord = ref({
  PARK_CODE: '',
  EQUIP_NAME: '',
  EQUIP_TYPE: '',
  LONGITUDE: '',
  LATITUDE: '',
})

const updateData = ref({
  id: '',
  PARK_CODE: '',
  EQUIP_NAME: '',
  EQUIP_TYPE: '',
  LONGITUDE: '',
  LATITUDE: '',
  UPDATE_BY: ''
})

const selectedItem = ref(null)

// 计算属性
const totalItems = computed(() => equipmentData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value)

const displayedPages = computed(() => {
  const range = 2
  const start = Math.max(1, currentPage.value - range)
  const end = Math.min(totalPages.value, currentPage.value + range)
  return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

const displayedEquipmentData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return equipmentData.value.slice(start, end)
})

// 辅助函数
const getEquipTypeText = (type) => {
  const types = {
    '1': '门禁',
    '2': '人员闸机',
    '3': '车辆卡口',
    '4': '车辆抓拍道闸'
  }
  return types[type] || ''
}

// API 调用函数
const searchEquipment = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    equipmentData.value = response.data
    currentPage.value = 1
    selectedIds.value = []
    selectAll.value = false
  } catch (error) {
    console.error('搜索设备记录失败:', error)
    alert('搜索设备记录失败')
  }
}

// 实现其他API调用函数，如addNewEquipment, deleteSelected, updateRecord等

// 事件处理函数
const resetSearch = () => {
  search.value = {
    PARK_CODE: '',
    EQUIP_NAME: '',
    EQUIP_TYPE: ''
  }
  searchEquipment()
}
const formItems = ref([
  {
    label: '园区编号：',
    model: 'PARK_CODE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '设备名称：',
    model: 'EQUIP_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '设备类型：',
    model: 'EQUIP_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '全部', value: '' },
      { label: '门禁', value: '1' },
      { label: '人员闸机', value: '2' },
      { label: '车辆卡口', value: '3' },
      { label: '车辆抓拍道闸一体机', value: '4' },
    ],
  },
]);

const openAddDialog = () => {
  isAddDialogOpen.value = true
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
  resetNewRecord()
}

const exportData = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new()

  // 准备导出数据
  const exportData = equipmentData.value.map(record => ({
    '园区编号': record.PARK_CODE,
    '设备名称': record.EQUIP_NAME,
    '设备类型': getEquipTypeText(record.EQUIP_TYPE),
    '经度': record.LONGITUDE,
    '纬度': record.LATITUDE,
    '创建人': record.CREATE_BY,
    '创建时间': record.CREATE_TIME,
    '更新人': record.UPDATE_BY,
    '更新时间': record.UPDATE_TIME
  }))

  // 转换为工作表
  const ws = XLSX.utils.json_to_sheet(exportData)

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, "门禁卡口信息")

  // 生成二进制字符串
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })

  // 转换为 Blob
  const blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" })

  // 创建下载链接
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '门禁卡口信息.xlsx'

  // 触发下载
  link.click()

  // 释放 URL
  URL.revokeObjectURL(link.href)
}

// 添加字符串转 ArrayBuffer 的辅助函数
function s2ab(s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF
  return buf
}

const viewDetails = (item) => {
  selectedItem.value = { ...item }
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  selectedItem.value = null
}

const loadRecordForUpdate = (item) => {
  updateData.value = { ...item, UPDATE_BY: 'admin' } // 假设更新人为 'admin'
  isEditDialogOpen.value = true
}

const closeEditDialog = () => {
  isEditDialogOpen.value = false
  updateData.value = {
    id: '',
    PARK_CODE: '',
    EQUIP_NAME: '',
    EQUIP_TYPE: '',
    LONGITUDE: '',
    LATITUDE: '',
    UPDATE_BY: ''
  }
}

const updateEquipment = async () => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/${updateData.value.ID}`, updateData.value)
    console.log('更新设备接收到的数据:', response.data)
    alert(response.data.message || '更新设备成功')
    closeEditDialog()
    await searchEquipment()
  } catch (error) {
    console.error('新设备失败:', error)
    alert('更新设备失败: ' + (error.response?.data?.message || error.message))
  }
}

const changePageSize = () => {
  currentPage.value = 1
  searchEquipment()
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    // searchEquipment()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    // searchEquipment()
  }
}

const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    searchEquipment()
  }
}

const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedIds.value = []
  } else {
    selectedIds.value = equipmentData.value.map(item => item.ID)
  }
  selectAll.value = !selectAll.value
}

const toggleItemSelection = (item) => {
  const index = selectedIds.value.indexOf(item.ID)
  if (index === -1) {
    selectedIds.value.push(item.ID)
  } else {
    selectedIds.value.splice(index, 1)
  }
  selectAll.value = selectedIds.value.length === equipmentData.value.length
}

const confirmDelete = async (id) => {
  if (confirm('确定要删除这条记录吗？')) {
    try {
      const response = await axios.delete(`${apiBaseUrl.value}/${id}`, {
        data: { UPDATE_BY: 'admin' }
      })
      console.log('删除设备接收到的数据:', response.data)
      alert(response.data.message || '删除设备成功')
      await searchEquipment()
    } catch (error) {
      console.error('删除设备失败:', error)
      alert('删除设备失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const resetNewRecord = () => {
  newRecord.value = {
    PARK_CODE: '',
    EQUIP_NAME: '',
    EQUIP_TYPE: '',
    LONGITUDE: '',
    LATITUDE: '',
    CREATE_BY: ''
  }
}

const validateCoordinate = (value, type) => {
  const num = parseFloat(value)
  if (isNaN(num)) {
    return `${type}必须是一个有效的数字`
  }
  if (type === '经度' && (num < -180 || num > 180)) {
    return '经度必须在 -180 到 180 之间'
  }
  if (type === '纬度' && (num < -90 || num > 90)) {
    return '纬度必须在 -90 到 90 之��'
  }
  return ''
}

const addNewEquipment = async () => {
  const longitudeError = validateCoordinate(newRecord.value.LONGITUDE, '经度')
  const latitudeError = validateCoordinate(newRecord.value.LATITUDE, '纬度')

  if (longitudeError || latitudeError) {
    alert(longitudeError || latitudeError)
    return
  }

  try {
    const response = await axios.post(apiBaseUrl.value, newRecord.value)
    console.log('新增设备接收到的数据:', response.data)
    alert(response.data.message || '创建记录成功')
    closeAddDialog()
    await searchEquipment()
  } catch (error) {
    console.error('创建记录失败:', error)
    alert('创建记录失败: ' + (error.response?.data?.message || error.message))
  }
}

// 删除选中的设备
const deleteSelected = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      const responses = await Promise.all(selectedIds.value.map(id =>
        axios.delete(`${apiBaseUrl.value}/${id.ID}`, { data: { UPDATE_BY: 'admin' } })
      ))
      console.log('删除选中记录接收到的数据:', responses.map(r => r.data))
      alert('删除成功')
      selectedIds.value = []
      selectAll.value = false
      await searchEquipment()
    } catch (error) {
      console.error('删除记录败:', error)
      alert('删除记录失败')
    }
  }
}

// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
};
const rules = {
  PARK_CODE: [
    { required: true, message: '请输入园区编号', trigger: 'blur' },
  ],
  EQUIP_NAME: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
  ],
  EQUIP_TYPE: [
    { required: true, message: '请选择设备类型', trigger: 'change' },
  ],
  LONGITUDE: [
    { required: true, message: '请输入经度', trigger: 'blur' },
  ],
  LATITUDE: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
  ],
};
const formRef = ref(null)
const isDialogType = ref('')
const loading = ref(false)
const handleSelectionChange = (selected) => {
  selectedIds.value = selected;
};
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}
const handleChange = (file, fileList) => {
  // 处理文件上传后的逻辑
  newRecord.value.PASS_IMG = file.name; // 这里可以根据需要调整
};

// 生命周期钩子
onMounted(() => {
  searchEquipment()
})

const selectedIds = ref([])

// 修改导入相关的函数
const importData = () => {
  // 创建一个隐藏的文件输入元素
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = '.xlsx, .xls, .csv'
  fileInput.style.display = 'none'

  // 监听文件选择事件
  fileInput.onchange = async (event) => {
    const file = event.target.files[0]
    if (!file) {
      return
    }

    const formData = new FormData()
    formData.append('file', file)

    try {
      const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      alert(response.data.message || '导入成功')
      await searchEquipment()
    } catch (error) {
      console.error('导入失败:', error)
      alert('导入失败: ' + (error.response?.data?.message || error.message))
    } finally {
      // 清理DOM
      document.body.removeChild(fileInput)
    }
  }

  // 添加到DOM并触发点击
  document.body.appendChild(fileInput)
  fileInput.click()
}
</script>

<style scoped>
.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}
</style>
